package com.hyh.web;

import com.hyh.bean.Users;
import com.hyh.service.impl.UsersServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收参数
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        //2.调取service
        UsersServiceImpl usersService = new UsersServiceImpl();
        Users users = usersService.login(userName, password);
        //3.跳转页面
        if (users == null){
            //以弹窗口方式提示用户，登录失败
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.println("<script>location.href='login.jsp';alert('用户或密码不正确！');</script>");
        }else {
            //保存用户信息
            HttpSession session = req.getSession();
            session.setAttribute("userName",userName);
            session.setAttribute("password",password);
            req.getSession().setAttribute("u1",users);
            //跳转到主页面
            resp.sendRedirect("index.jsp");
        }
    }
}
